<?php

class VendorController extends PsController
{

	public $layout = 'manage';

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'users' => array('@'),
					//'roles' => array('Transactions.ViewOwn'),
					)), parent::accessRules());
	}

	public function moduleAccessRules()
	{
		return array();
	}

	public function actionView($id)
	{
		$this->render('view', array(
			'vendor' => $this->loadVendor($id),
		));
	}

	public function actionCreate()
	{
		$vendor = new Vendor;

		if (isset($_POST['Vendor'])) {
			$vendor->setAttributes($_POST['Vendor']);
			
			$vendor->agency_id = Yii::app()->user->model->agency_id;

			if ($vendor->isNewRecord) {
				$party = new Party();
				$party->type = 'Vendor';
				$party->save();

				$vendor->party_id = $party->id;
			}

			if ($vendor->save()) {
				$this->redirect(array('view', 'id' => $vendor->id));
				PsSystemMessage::add("Vendor Added.", 'success');
			}
		}

		$this->render('create', array('vendor' => $vendor));
	}

	public function actionUpdate($id)
	{
		$vendor = $this->loadVendor($id);


		if (isset($_POST['Vendor'])) {
			$vendor->setAttributes($_POST['Vendor']);

			if ($vendor->save()) {
				$this->redirect(array('view', 'id' => $vendor->id));
			}
		}

		$this->render('update', array(
			'vendor' => $vendor,
		));
	}

	public function actionDelete($id)
	{
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			$this->loadVendor($id)->delete();

			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('admin'));
		}
		else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}

	public function actionIndex()
	{
		$vendor = new Vendor('search');
		$vendor->unsetAttributes();

		if (isset($_GET['Vendor']))
			$vendor->setAttributes($_GET['Vendor']);

		$this->render('index', array(
			'vendor' => $vendor,
		));
	}

	/**
	 * Loads the Vendor AR model
	 * @param integer $id the primary key
	 * @return Vendor	 */
	public function loadVendor($id)
	{
		//$vendor = Vendor::model()->ofCurrentUser()->findByPk($id);
		$vendor = Vendor::model()->findByPk($id);

		if ($vendor == null) {
			throw new PsPageNotFoundException();
		}

		return $vendor;
	}

}